package com.foodapp.back.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.foodapp.back.common.Result;
import com.foodapp.back.dto.OrderCreateDTO;
import com.foodapp.back.service.OrderService;
import com.foodapp.back.vo.OrderVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping
    public Result<Long> create(@RequestBody @Valid OrderCreateDTO orderCreateDTO, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        Long orderId = orderService.createOrder(userId, orderCreateDTO);
        return Result.success(orderId);
    }

    /**
     * 分页查询用户订单列表
     */
    @GetMapping("/list")
    public Result<Page<OrderVO>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            HttpServletRequest request) {
        
        Long userId = (Long) request.getAttribute("userId");
        Page<OrderVO> result = orderService.getUserOrderList(userId, page, size, status);
        return Result.success(result);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public Result<OrderVO> getById(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        OrderVO orderVO = orderService.getOrderDetail(id);
        
        // 校验订单所属
        if (!orderVO.getUserId().equals(userId)) {
            return Result.error(403, "无权访问此订单");
        }
        
        return Result.success(orderVO);
    }

    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public Result<Boolean> cancel(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        boolean result = orderService.cancelOrder(userId, id);
        return Result.success(result);
    }

    /**
     * 支付订单
     */
    @PutMapping("/{id}/pay")
    public Result<Boolean> pay(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        boolean result = orderService.payOrder(userId, id);
        return Result.success(result);
    }
}
